package org.lifxue.jqda.ui;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;

import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import org.lifxue.jqda.data.DataUtil;
import org.lifxue.jqda.data.bean.AppInfoBean;
import org.lifxue.jqda.util.GlobalVar;

/**
 * 
 * @Description:
 * @Author: zhangzuoqiang
 * @Date: Sep 26, 2011
 */
public class QuickStartListDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// private static Log logger =
	// LogFactory.getLog(QuickStartListDialog.class);

	private static QuickStartListDialog QSList;

	public static QuickStartListDialog getInstance(boolean modal) {
		synchronized (QuickStartListDialog.class) {
			if (QSList == null) {
				QSList = new QuickStartListDialog(modal);
			}
		}
		return QSList;
	}

	public QuickStartListDialog(boolean modal) {
		super(new JFrame(), modal);

		initComponents();
		initTableData();

		// 屏幕位置
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		Dimension frameSize = getSize();
		setLocation(new Point((screenSize.width - frameSize.width) / 2,
				(screenSize.height - frameSize.width) / 2));

	}

	/** Creates new form QuickStartListDialog */
	public QuickStartListDialog(Frame parent, boolean modal) {
		super(parent, modal);
		initComponents();

	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */
	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new JScrollPane();
		jTable1 = new JTable();
		addjButton = new JButton();
		deljButton = new JButton();
		canceljButton = new JButton();
		savejButton = new JButton();
		scanjButton = new JButton();

		setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
		setTitle("快速启动程序列表");

		jTable1.setModel(new DefaultTableModel(new Object[][] {

		}, new String[] { "名称", "路径", "次数" }) {
			/**
					 * 
					 */
			private static final long serialVersionUID = 1L;
			Class<?>[] types = new Class[] { String.class, String.class,
					String.class };
			boolean[] canEdit = new boolean[] { false, false, false };

			public Class<?> getColumnClass(int columnIndex) {
				return types[columnIndex];
			}

			public boolean isCellEditable(int rowIndex, int columnIndex) {
				return canEdit[columnIndex];
			}
		});
		jScrollPane1.setViewportView(jTable1);
		jTable1.getColumnModel().getColumn(0).setPreferredWidth(30);
		jTable1.getColumnModel().getColumn(1).setPreferredWidth(200);
		jTable1.getColumnModel().getColumn(2).setMinWidth(50);
		jTable1.getColumnModel().getColumn(2).setPreferredWidth(10);
		jTable1.getColumnModel().getColumn(2).setMaxWidth(50);

		addjButton.setText("增加");
		addjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				addjButtonActionPerformed(evt);
			}
		});

		deljButton.setText("删除");
		deljButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				deljButtonActionPerformed(evt);
			}
		});

		canceljButton.setText("取消");
		canceljButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				canceljButtonActionPerformed(evt);
			}
		});

		savejButton.setText("保存");
		savejButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				savejButtonActionPerformed(evt);
			}
		});

		scanjButton.setText("自动扫描文件");
		scanjButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				scanjButtonActionPerformed(evt);
			}
		});

		GroupLayout layout = new GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.LEADING)
												.addComponent(
														jScrollPane1,
														GroupLayout.DEFAULT_SIZE,
														709, Short.MAX_VALUE)
												.addGroup(
														layout.createSequentialGroup()
																.addComponent(
																		addjButton)
																.addGap(18, 18,
																		18)
																.addComponent(
																		deljButton)
																.addGap(18, 18,
																		18)
																.addComponent(
																		scanjButton)
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED,
																		347,
																		Short.MAX_VALUE)
																.addComponent(
																		savejButton)
																.addGap(18, 18,
																		18)
																.addComponent(
																		canceljButton)))
								.addContainerGap()));
		layout.setVerticalGroup(layout
				.createParallelGroup(GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jScrollPane1,
										GroupLayout.PREFERRED_SIZE, 324,
										GroupLayout.PREFERRED_SIZE)
								.addGroup(
										layout.createParallelGroup(
												GroupLayout.Alignment.TRAILING)
												.addGroup(
														layout.createSequentialGroup()
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						addjButton)
																				.addComponent(
																						deljButton)
																				.addComponent(
																						scanjButton))
																.addContainerGap(
																		33,
																		Short.MAX_VALUE))
												.addGroup(
														layout.createSequentialGroup()
																.addPreferredGap(
																		LayoutStyle.ComponentPlacement.RELATED)
																.addGroup(
																		layout.createParallelGroup(
																				GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						canceljButton)
																				.addComponent(
																						savejButton))
																.addContainerGap()))));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void addjButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_addjButtonActionPerformed
		// TODO add your handling code here:
		// 建立文件选择框对象
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
		FileNameExtensionFilter filter = new FileNameExtensionFilter("可执行文件",
				"exe", "bat", "lnk");
		fc.setFileFilter(filter);

		// 设定文件选择框标题
		fc.setDialogTitle("选择可执行文件");
		// 显示文件选择框，在选择后将结果储存到returnVal变量中
		int returnVal = fc.showSaveDialog(this);
		// 如果用户选择了文件，并点击了"Opne/打开"按钮，显示用户选择的文件全名路径，
		// 如果用户点击"Close/关闭"按钮，以及其它方式退出文件选择框，则什么也不做。
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			if (file == null) {
				return;
			}
			if (isExistPath(file)) {
				int type = JOptionPane.CLOSED_OPTION;
				String message = "你选择的文件已经在表格中了！";
				JOptionPane.showConfirmDialog(this, message, "提示信息", type);
				return;
			}
			addTableRow(file);

		}

	}// GEN-LAST:event_addjButtonActionPerformed

	private void canceljButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_canceljButtonActionPerformed
		// TODO add your handling code here:
		setVisible(false);
		dispose();
		QSList = null;

	}// GEN-LAST:event_canceljButtonActionPerformed

	private void deljButtonActionPerformed(ActionEvent evt) {
		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		int allcount = model.getRowCount();
		int row = jTable1.getSelectedRow();
		if (row < 0) {
			return;
		}
		model.removeRow(row);
		model.setRowCount(allcount - 1);
	}

	private void savejButtonActionPerformed(ActionEvent evt) {
		// 保存数据到文件和全局变量中
		HashMap<String, List<AppInfoBean>> QS_APP = new HashMap<String, List<AppInfoBean>>();

		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		int allcount = model.getRowCount();
		for (int i = allcount - 1; i >= 0; i--) {
			String name = (String) model.getValueAt(i, 0);
			String path = (String) model.getValueAt(i, 1);
			String VolumeOfUse = (String) model.getValueAt(i, 2);
			int num = Integer.parseInt(VolumeOfUse);

			List<AppInfoBean> pathlist = (List<AppInfoBean>) QS_APP.get(name);
			if (pathlist == null || pathlist.isEmpty()) {
				pathlist = new ArrayList<AppInfoBean>();
				AppInfoBean appinfo = new AppInfoBean();
				appinfo.setPath(path);
				appinfo.setVolumeOfUse(num);
				pathlist.add(appinfo);
				QS_APP.put(name, pathlist);
			} else {
				AppInfoBean appinfo = new AppInfoBean();
				appinfo.setPath(path);
				appinfo.setVolumeOfUse(num);
				pathlist.add(appinfo);
				QS_APP.put(name, pathlist);
			}
		}
		GlobalVar.APPLICATIONS = QS_APP;
		// logger.debug(QS_APP);
		// logger.debug(GlobalVar.APPLICATIONS);
		DataUtil.updateAppsFile();
		// 关闭QuickStartJFrame实例
		QuickStartJFrame qs = QuickStartJFrame.getInstance();
		qs.updateData();

		canceljButtonActionPerformed(evt);

	}// GEN-LAST:event_savejButtonActionPerformed

	private void scanjButtonActionPerformed(ActionEvent evt) {// GEN-FIRST:event_scanjButtonActionPerformed
		// TODO add your handling code here:
		QuickStartSettingJDialog qs = QuickStartSettingJDialog
				.getInstance(true);
		qs.setVisible(true);
	}// GEN-LAST:event_scanjButtonActionPerformed

	private void addTableRow(File file) {
		Object[] obj = new Object[3];
		obj[0] = file.getName().toLowerCase(Locale.CHINESE);
		obj[1] = file.getPath();
		obj[2] = "0";

		((DefaultTableModel) jTable1.getModel()).addRow(obj);

	}

	private boolean isExistPath(File file) {
		boolean exist = false;
		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		int allcount = model.getRowCount();
		for (int i = allcount - 1; i >= 0; i--) {
			Object temp = model.getValueAt(i, 1);
			if (temp.toString().equals(file.getPath())) {
				exist = true;
				break;
			}
		}
		return exist;
	}

	/**
	 * 初始化表格数据
	 */
	public void initTableData() {
		DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
		model.getDataVector().removeAllElements();
		Iterator<Entry<String, List<AppInfoBean>>> i = GlobalVar.APPLICATIONS
				.entrySet().iterator();
		while (i.hasNext()) {
			Object[] obj = new Object[3];
			Entry<String, List<AppInfoBean>> entry = (Entry<String, List<AppInfoBean>>) i
					.next();
			String key = (String) entry.getKey(); // 返回与此项对应的键
			List<AppInfoBean> pathlist = (List<AppInfoBean>) entry.getValue(); // 返回与此项对应的值
			for (AppInfoBean value : pathlist) {
				obj[0] = key;
				obj[1] = value.getPath();
				obj[2] = String.valueOf(value.getVolumeOfUse());
				model.addRow(obj);
			}
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		EventQueue.invokeLater(new Runnable() {

			public void run() {
				QuickStartListDialog dialog = new QuickStartListDialog(
						new JFrame(), true);
				dialog.addWindowListener(new WindowAdapter() {

					public void windowClosing(WindowEvent e) {
						System.exit(0);
					}
				});
				dialog.setVisible(true);
			}
		});
	}

	private JButton addjButton;
	private JButton canceljButton;
	private JButton deljButton;
	private JScrollPane jScrollPane1;
	private JTable jTable1;
	private JButton savejButton;
	private JButton scanjButton;
}
